<template>
  <div class="paper-grading-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-info">
            <h3>{{ examInfo.name }}</h3>
            <span class="student-info">
              考生：{{ paperInfo.studentName }}（{{ paperInfo.studentId }}）
            </span>
          </div>
          <div class="header-actions">
            <span class="total-score">总分：{{ totalScore }}/100</span>
            <el-button type="primary" @click="handleSave">保存</el-button>
            <el-button @click="handleNext">下一份</el-button>
          </div>
        </div>
      </template>

      <!-- 答题情况 -->
      <div class="questions-container">
        <div
          v-for="(question, index) in paperInfo.questions"
          :key="question.id"
          class="question-item"
        >
          <div class="question-header">
            <span class="question-title">
              第{{ index + 1 }}题（{{ question.score }}分）
            </span>
            <div class="score-input">
              <span>得分：</span>
              <el-input-number
                v-if="question.type === 'programming'"
                v-model="question.gotScore"
                :min="0"
                :max="question.score"
                :step="0.5"
                size="small"
              />
              <span v-else>{{ question.gotScore }}</span>
            </div>
          </div>

          <div class="question-content">
            <p class="question-text">{{ question.title }}</p>
            
            <!-- 选择题答案 -->
            <template v-if="['single', 'multiple'].includes(question.type)">
              <div
                v-for="option in question.options"
                :key="option.id"
                :class="['option-item', {
                  'student-selected': isOptionSelected(question, option.id),
                  'correct-answer': isCorrectAnswer(question, option.id)
                }]"
              >
                {{ option.content }}
              </div>
            </template>

            <!-- 填空题答案 -->
            <template v-if="question.type === 'blank'">
              <div class="answer-comparison">
                <div class="answer-item">
                  <span class="answer-label">学生答案：</span>
                  <span :class="['answer-content', {
                    'correct': question.studentAnswer === question.correctAnswer
                  }]">
                    {{ question.studentAnswer }}
                  </span>
                </div>
                <div class="answer-item">
                  <span class="answer-label">正确答案：</span>
                  <span class="answer-content correct">
                    {{ question.correctAnswer }}
                  </span>
                </div>
              </div>
            </template>

            <!-- 编程题答案 -->
            <template v-if="question.type === 'programming'">
              <div class="programming-answer">
                <el-tabs v-model="question.activeTab">
                  <el-tab-pane label="代码" name="code">
                    <pre class="code-block">{{ question.studentAnswer }}</pre>
                  </el-tab-pane>
                  <el-tab-pane label="运行结果" name="result">
                    <div class="test-cases">
                      <div
                        v-for="(testCase, idx) in question.testCases"
                        :key="idx"
                        class="test-case-item"
                      >
                        <div class="test-case-header">
                          <span>测试用例 #{{ idx + 1 }}</span>
                          <el-tag
                            :type="testCase.passed ? 'success' : 'danger'"
                          >
                            {{ testCase.passed ? '通过' : '未通过' }}
                          </el-tag>
                        </div>
                        <div class="test-case-content">
                          <p><strong>输入：</strong>{{ testCase.input }}</p>
                          <p><strong>期望输出：</strong>{{ testCase.expectedOutput }}</p>
                          <p><strong>实际输出：</strong>{{ testCase.actualOutput }}</p>
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </template>

            <!-- 评语 -->
            <div class="comment-section">
              <el-input
                v-model="question.comment"
                type="textarea"
                :rows="2"
                placeholder="添加评语（可选）"
              />
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 考试信息
const examInfo = reactive({
  id: route.params.examId,
  name: 'C语言期中考试'
})

// 试卷信息
const paperInfo = reactive({
  studentId: '2024001',
  studentName: '张三',
  questions: [
    {
      id: 1,
      type: 'single',
      title: '以下哪个不是C语言的基本数据类型？',
      score: 2,
      gotScore: 2,
      options: [
        { id: 1, content: 'int' },
        { id: 2, content: 'float' },
        { id: 3, content: 'string' },
        { id: 4, content: 'char' }
      ],
      studentAnswer: [3],
      correctAnswer: [3],
      comment: ''
    },
    {
      id: 2,
      type: 'programming',
      title: '请编写一个函数，实现冒泡排序算法。',
      score: 10,
      gotScore: 8,
      studentAnswer: `void bubbleSort(int arr[], int n) {
    for(int i = 0; i < n-1; i++) {
        for(int j = 0; j < n-i-1; j++) {
            if(arr[j] > arr[j+1]) {
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}`,
      testCases: [
        {
          input: '[5, 2, 8, 1, 9]',
          expectedOutput: '[1, 2, 5, 8, 9]',
          actualOutput: '[1, 2, 5, 8, 9]',
          passed: true
        },
        {
          input: '[3, 3, 1, 2, 2]',
          expectedOutput: '[1, 2, 2, 3, 3]',
          actualOutput: '[1, 2, 2, 3, 3]',
          passed: true
        }
      ],
      activeTab: 'code',
      comment: '算法实现正确，但可以优化性能'
    }
  ]
})

// 计算总分
const totalScore = computed(() => {
  return paperInfo.questions.reduce((sum, q) => sum + q.gotScore, 0)
})

const isOptionSelected = (question, optionId) => {
  return question.studentAnswer.includes(optionId)
}

const isCorrectAnswer = (question, optionId) => {
  return question.correctAnswer.includes(optionId)
}

const handleSave = async () => {
  try {
    // 实现保存逻辑
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败：' + error.message)
  }
}

const handleNext = () => {
  // 实现切换到下一份试卷的逻辑
  ElMessage.info('已是最后一份试卷')
}
</script>

<style scoped>
.paper-grading-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-info h3 {
  margin: 0 0 10px 0;
}

.student-info {
  color: #606266;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-score {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.question-item {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.question-title {
  font-weight: bold;
}

.question-text {
  margin-bottom: 15px;
}

.option-item {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
}

.student-selected {
  background-color: #FEF0F0;
  border-color: #F56C6C;
}

.correct-answer {
  background-color: #F0F9EB;
  border-color: #67C23A;
}

.answer-comparison {
  margin: 15px 0;
}

.answer-item {
  margin: 10px 0;
}

.answer-label {
  font-weight: bold;
  margin-right: 10px;
}

.answer-content {
  padding: 5px 10px;
  background-color: #F5F7FA;
  border-radius: 4px;
}

.answer-content.correct {
  color: #67C23A;
}

.programming-answer {
  margin: 15px 0;
}

.code-block {
  padding: 15px;
  background-color: #F5F7FA;
  border-radius: 4px;
  font-family: monospace;
  white-space: pre-wrap;
}

.test-cases {
  margin: 15px 0;
}

.test-case-item {
  margin-bottom: 15px;
  padding: 15px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
}

.test-case-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.test-case-content p {
  margin: 5px 0;
}

.comment-section {
  margin-top: 15px;
}
</style> 